package com.hunan.chinamobile.core;

import com.alibaba.druid.util.StringUtils;
import com.hunan.chinamobile.constant.SysConstant;
import com.hunan.chinamobile.dto.UserDTO;
import com.hunan.chinamobile.model.City;
import com.hunan.chinamobile.security.TokenAuthenticationService;
import com.hunan.chinamobile.service.CityService;
import com.hunan.chinamobile.service.HUserService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
public class BaseController {

    @Resource
    private HUserService hUserService;
    @Resource
    private CityService cityService;

    public UserDTO getUser(HttpServletRequest request, HttpServletResponse response){
        Authentication authentication = TokenAuthenticationService.getAuthentication(request, response);
        if (authentication == null) {
            return null;
        }
        UserDTO userDTO = hUserService.findByUserName(authentication.getPrincipal().toString());
        if(!StringUtils.isEmpty(userDTO.getCityId())){
            City city = cityService.findById(userDTO.getCityId());
            userDTO.setCityName(city.getCityName());
        }
        return userDTO;
    }

    public String getCityId(HttpServletRequest request, HttpServletResponse response){
        UserDTO userDTO = getUser(request, response);
        if(userDTO == null) throw new ServiceException("请登录");
        if(userDTO.getRoleName().equals(SysConstant.ROLE_USER))
            return userDTO.getCityId();
        return null;
    }
}
